<?php
namespace App\Admin\Controllers\Products;

use App\Admin\Actions\Products\SkuSupplier\ImportSkuSupplier;
use App\Admin\Extensions\Grid\Tool\Export;
use App\Models\Product\ProductClassify;
use App\Models\Product\ProductSku;
use App\Models\Product\ProductSupplier;
use App\Util\RExcel;
use Encore\Admin\Controllers\AdminController;
use App\Models\Basics\Supplier;
use Encore\Admin\Grid;
use Encore\Admin\Form;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Support\Facades\Request;

class SkuSupplierController extends AdminController{

    protected $title = '产品供应商';

    protected function grid()
    {
        $grid = new Grid(new ProductSupplier());
        $grid->model()->newQuery()->orderBy('ID', 'DESC');
        $grid->model()->collection(function (Collection $collection){
            foreach($collection as $item) {
                $item->self_price = numberFormat(round($item->unit_price - $item->supplier_price,3));
            }
            return $collection;
        });
        $grid->column('id','ID')->sortable();
        $grid->column('psku_id','SKU ID')->sortable();
        $grid->column('sku.psku_code','SKU');
        $grid->column('sku.psku_cn','名称')->style('max-width:200px');
        $grid->column('sku.classify_id','品类')->display(function ($value){
            return ProductClassify::getTitleById($value);
        });
        $grid->column('supplier_id','供应商ID')->sortable();
        $grid->column('supplier.code','供应商编码');
        $grid->column('supplier.name','供应商名称')->style('max-width:200px');
        $grid->column('supplier.type','供应商类型')->using(Supplier::$_type);
        $grid->column('moq','最小起订量');
        $grid->column('supplier_price','供应商单价');
        $grid->column('self_price','自购单价');
        $grid->column('unit_price','总采购单价');
        $grid->column('purchase_cycle','采购周期');
        $grid->column('status','是否默认')->using(ProductSupplier::$_status)->filter(ProductSupplier::$_status);
        $grid->tools(function (Grid\Tools $tools) {
            $tools->append(new ImportSkuSupplier());
        });
        $grid->fixHeader();
        $grid->disableExport();
        $grid->tools(function (Grid\Tools $tools){
            $tools->append(new Export('products/sku-supplier-download'));
        });
        $grid->actions(function (Grid\Displayers\Actions $actions) {
            $actions->disableView();
        });
        $grid->filter(function($filter){
            $filter->column(1/3, function ($filter){
                $filter->where(function ($query) {
                    $query->whereHas('sku', function ($query) {
                        $query->where('psku_code', 'like', "%{$this->input}%")
                            ->orWhere('psku_cn', 'like', "%{$this->input}%");
                    });
                }, '查询','sku8')->placeholder('模糊查询SKU，名称');
                $filter->equal('sku.classify_id', '品类')->select(ProductClassify::options());
            });
            $filter->column(1/3, function ($filter) {
                $filter->equal('supplier_id', '供应商名称')->select(Supplier::options());
                //$filter->equal('supplier.type', '供应商类型')->select(Supplier::$_type);
            });
            $filter->column(1/3, function ($filter) {
                $filter->in('sku.is_mix', '组合')->checkbox(ProductSku::$_isMix);
            });
        });

        return $grid;
    }

    protected function form()
    {
        $form = new Form(new ProductSupplier());
        $form->hidden('id');
        if($form->isCreating()){
            $form->select('psku_id', 'SKU')
                ->options(function ($id) {
                    $id = $id ?: old('psku_id');
                    $ps = ProductSku::getModelById($id);
                    if ($ps) {
                        return [$ps->id => $ps->psku_code];
                    }else{
                        return [];
                    }
                })->ajax('/xqc/api-sys/products-sku-supplier')
                ->rules('required');
        }else{
            $form->display('sku.psku_code', 'SKU');
        }
        $form->select('supplier_id','供应商')->options(Supplier::options(false))->rules('required');
        $form->number('moq','最小起订量')->default(1)->min(1)->rules('required|gt:0');
        $form->decimal('supplier_price','供应商单价')->options(['digits'=>3])->attribute(['maxlength'=>8])->rules('required|gt:0');
        $form->decimal('unit_price','总采购单价')->options(['digits'=>3])->attribute(['maxlength'=>8])->rules('required|gt:0');
        $form->number('purchase_cycle','采购周期(天)')->default(1)->min(1)->rules('required|gt:0');
        $form->radio('status','是否默认')->default(0)->options(ProductSupplier::$_status)
            ->help("若选择为‘是’则该产品其他供应商均自动为‘否’");
        $form->saved(function (Form $form) {
            if($form->model()->status == 1){
                ProductSupplier::modifyDefaultPuSupplier($form->model()->id,$form->model()->psku_id);
            }
        });
        if($form->isCreating()){
            $form->disableCreatingCheck(false);
        }
        $form->tools(function (Form\Tools $tools) {
            $tools->disableView();
        });
        return $form;
    }

    public function download(){
        $request = Request::input();
        $query = $this->_initQuery($request);
        $this->_exeDownload($query);
    }

    private function _initQuery($filters){
        $query = ProductSupplier::query()->orderBy('id', 'DESC');

        foreach ($filters as $key => $_filter){
            //if($key == 'supplier'){
            //    $query->whereHas('supplier', function ($query) use($_filter){
            //        foreach ($_filter as $filed => $filter){
            //            if(in_array($filed,['type'])){
            //                $query->where('type',$filter);
            //            }
            //        }
            //    });
            //}
            if($key == 'sku8'){
                $query->whereHas('sku', function ($query) use($_filter){
                    $query->where('psku_code', 'like', "%{$_filter}%")
                        ->orWhere('psku_cn', 'like', "%{$_filter}%");
                });
            }
            if($key == 'sku'){
                $query->whereHas('sku', function ($query) use($_filter){
                    foreach ($_filter as $filed => $filter){
                        if(in_array($filed,['is_mix'])){
                            $query->whereIn($filed, $filter);
                        }else{
                            $query->where($filed, $filter);
                        }
                    }
                });
            }
            if(in_array($key,['supplier_id'])){
                $query->where($key,$_filter);
            }
        }
        return $query;
    }

    private function _exeDownload($query){
        $head = ['SKU','名称','组合','品类','供应商编码','供应商名称','供应商类型','最小起订量','供应商单价','自购单价','总采购单价','采购周期','是否默认'];
        RExcel::exportCsv('产品供应商',function () use ($head, $query) {
            $fp = fopen('php://output', 'w');
            fwrite($fp, chr(0xEF).chr(0xBB).chr(0xBF));
            fputcsv($fp, $head);
            $query->chunk(1000, function ($re) use ($fp){
                $data = self::getDownloadData($re);
                foreach ($data as $item) {
                    fputcsv($fp, $item);
                }
            });
        });
    }

    public static function getDownloadData($res)
    {
        $classify = [];
        foreach ($res as $model){
            $classifyId = $model->sku->classify_id ?? '';
            if(!array_key_exists($classifyId,$classify)){
                $classify[$classifyId] = ProductClassify::getTitleById($classifyId);
            }
            $temp = [
                $model->sku->psku_code ?? '',
                $model->sku->psku_cn ?? '',
                ProductSku::$_isMix[$model->sku->is_mix ?? 0],
                $classify[$classifyId],
                $model->supplier->code ?? '',
                $model->supplier->name ?? '',
                Supplier::$_type[$model->supplier->type] ?? '',
                $model->moq,
                $model->supplier_price,
                round($model->unit_price - $model->supplier_price,3),
                $model->unit_price,
                $model->purchase_cycle,
                ProductSupplier::$_status[$model->status],
            ];
            yield $temp;
        }
    }
}
